package com.itheima.health.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * @author ：roots
 * @date ：Created in 2020/1/2/17:40
 * @description ：分布式锁
 * @version: 1.0
 */
@Slf4j
public class LockManager {
    /**
     * 环绕通知
     * @param pjp
     * @return
     */
    public Object aroundPrintLog(ProceedingJoinPoint pjp){

        //构造超时重试策略，每1s重试一次，重试10次
        RetryPolicy retryPolicy = new RetryNTimes(10,1000);
        //构造客户端
        CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181",retryPolicy);
        // 启动客户端
        client.start();

        //构造锁
        InterProcessLock lock = new InterProcessMutex(client,"/user/1/update");


        //定义返回值
        Object rtValue = null;
        try{
            //前置通知，加锁
            log.debug("加锁成功");
            lock.acquire();
            log.debug("进入方法");
            //1.获取参数
            Object[] args = pjp.getArgs();
            //2.执行切入点方法
            rtValue = pjp.proceed(args);

            //后置通知，无
        }catch (Throwable t){
            //异常通知
            t.printStackTrace();
        }finally {
            //最终通知，释放锁
            try {
                lock.release();
                log.debug("释放锁成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return  rtValue;
    }

}
